package com.ht.utils;


import org.apache.commons.lang3.StringUtils;
import org.eclipse.angus.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.List;
import java.util.Properties;


/*
 * 邮箱发送辅助类
 */
public class MailUtil {

    /**
     * 发送电子邮件
     *
     * @param smtpHost
     *            发信主机
     * @param receiver
     *            邮件接收者
     * @param title
     *            邮件的标题
     * @param content
     *            邮件的内容
     * @param sender
     *            邮件发送者
     * @param user
     *            发送者邮箱用户名
     * @param pwd
     *            发送者邮箱密码
     */
    public static void sendEmail(String smtpHost, String receiver,
                                 String title, String content, String sender, String user, String pwd) throws MessagingException
    {
        Properties props = new Properties();
        props.put("mail.host", smtpHost);
        props.put("mail.transport.protocol", "smtp");
        // props.put("mail.smtp.host",smtpHost);//发信的主机，这里要把您的域名的SMTP指向正确的邮件服务器上，这里一般不要动！
        props.put("mail.smtp.auth", "true");
        // 解决阿里云服务器端口问题
        props.put("mail.smtp.port", 465);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        Session s = Session.getInstance(props);
        s.setDebug(true);
        MimeMessage message = new MimeMessage(s);
        // 给消息对象设置发件人/收件人/主题/发信时间
        // 发件人的邮箱
        InternetAddress from = new InternetAddress(sender);
        message.setFrom(from);
        InternetAddress to = new InternetAddress(receiver);
        message.setRecipient(Message.RecipientType.TO, to);
        // message.setSubject(title);
        try {
            message.setSubject(MimeUtility.encodeText(title,"gb2312","B"));
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        message.setSentDate(new Date());
        //防止成为垃圾邮件，披上outlook的马甲
        message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
        // 给消息对象设置内容
        BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
        mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
        Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
        // 象(事实上可以存放多个)
        mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
        message.setContent(mm);// 把mm作为消息对象的内容

        message.saveChanges();
        Transport transport = s.getTransport("smtp");
        transport.connect(smtpHost, user, pwd);// 设置发邮件的网关，发信的帐户和密码，这里修改为您自己用的
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     * 发送电子邮件
     *
     * @param smtpHost
     *            发信主机
     * @param receiver
     *            邮件接收者
     * @param copy
     *            抄送列表
     * @param title
     *            邮件的标题
     * @param content
     *            邮件的内容
     * @param sender
     *            邮件发送者
     * @param user
     *            发送者邮箱用户名
     * @param pwd
     *            发送者邮箱密码
     * @throws Exception
     */
    public static void sendEmail(String smtpHost, String receiver, String copy,
                                 String title, String content, String sender, String user, String pwd)
            throws Exception {
        Properties props = new Properties();
        props.put("mail.host", smtpHost);
        props.put("mail.transport.protocol", "smtp");
        // props.put("mail.smtp.host",smtpHost);//发信的主机，这里要把您的域名的SMTP指向正确的邮件服务器上，这里一般不要动！
        props.put("mail.smtp.auth", "true");
        // 解决阿里云服务器端口问题
        props.put("mail.smtp.port", 465);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        Session s = Session.getInstance(props);
        s.setDebug(true);
        MimeMessage message = new MimeMessage(s);
        // 给消息对象设置发件人/收件人/主题/发信时间
        // 发件人的邮箱
        InternetAddress from = new InternetAddress(sender);
        message.setFrom(from);
        //防止成为垃圾邮件，披上outlook的马甲
        message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
        String[] receivers = receiver.split(",");
        InternetAddress[] to = new InternetAddress[receivers.length];
        for (int i = 0; i < receivers.length; i++) {
            to[i] = new InternetAddress(receivers[i]);
        }
        message.setRecipients(Message.RecipientType.TO, to);

        String[] copys = copy.split(",");
        InternetAddress[] cc = new InternetAddress[copys.length];
        for (int i = 0; i < copys.length; i++) {
            cc[i] = new InternetAddress(copys[i]);
        }
        message.setRecipients(Message.RecipientType.CC, cc);

        try {
            message.setSubject(MimeUtility.encodeText(title,"gb2312","B"));
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        message.setSentDate(new Date());
        // 给消息对象设置内容
        BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
        mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
        Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
        // 象(事实上可以存放多个)
        mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
        message.setContent(mm);// 把mm作为消息对象的内容

        message.saveChanges();
        Transport transport = s.getTransport("smtp");
        transport.connect(smtpHost, user, pwd);// 设置发邮件的网关，发信的帐户和密码，这里修改为您自己用的
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     *
     * @param from  发件人
     * @param pass	发件人密码
     * @param host	端口
     * @param receive 收件人
     * @param subject  邮件主题
     * @param msg 邮件内容
     */
    public static boolean sendMailWithFile(String from,String pass,String host,String receive, String subject, String msg, List<File> attachments)
            throws GeneralSecurityException {
        if (StringUtils.isEmpty(receive)) {
            return false;
        }

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 解决阿里云服务器端口问题
        properties.put("mail.smtp.port", 465);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        // 获取默认session对象
        Session session = Session.getInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() { // qq邮箱服务器账户、第三方登录授权码
                return new PasswordAuthentication(from, pass); // 发件人邮件用户名、密码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));

            // Set Subject: 主题文字
            //message.setSubject(subject);
            try {
                message.setSubject(MimeUtility.encodeText(subject,"gb2312","B"));
            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
            //防止成为垃圾邮件，披上outlook的马甲
            message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");

            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
            messageBodyPart.setText(msg);

            // 创建多重消息
            Multipart multipart = new MimeMultipart();

            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart);

            // 附件部分
            messageBodyPart = new MimeBodyPart();


            if(attachments != null) {
                for(File attachment : attachments) {
                    BodyPart attachmentPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachment);
                    attachmentPart.setDataHandler(new DataHandler(source));
                    //避免中文乱码的处理
                    attachmentPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                    multipart.addBodyPart(attachmentPart);
                }
            }
            // 发送完整消息
            message.setContent(multipart);

            // 发送消息
            Transport.send(message);
            // System.out.println("Sent message successfully....");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public static void main(String[] args) {
        try {
//			sendEmail("smtp.126.com", "411944058@qq.com", "系统测试邮件",
//					"hi,all,I am AnChao!111", "anchaodaren@126.com",
//					"anchaodaren", "*******************");
            sendEmail("smtp.163.com", "418799587@qq.com", "系统测试邮件",
                    "hi,all,I am AnChao!111", "tjrzlm@163.com",
                    "tjrzlm", "tj123456");
//			PropertiesUtil util = new PropertiesUtil("sysConfig.properties");
//			sendEmail(util.readProperty("mail.smtpHost"), "411944058@qq.com","系统测试邮件",
//					"hi,all,I am AnChao!nana", util.readProperty("mail.sender"),
//					util.readProperty("mail.user"), util.readProperty("mail.pwd"));
        } catch (Exception e) {
        }
    }
}
